package com.llsydn.demo.downApk;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.llsydn.hello.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author lilinshen
 * @title 直接下载apk，并安装
 * @description 请填写相关描述
 * @date 2018/9/27 8:50
 */
public class DownApkActivity extends AppCompatActivity {

    private File apkFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_down_apk);
    }


    /**
     * 下载apk并安装
     *
     * @param view
     */
    public void downLoadApk(View view) {
        //1.主线程，显示提示视图：水平进度条
        ProgressDialog dialog = new ProgressDialog(this);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.show();

        //准备用于保存APK文件到File对象：/storage/sdcard/Android/packageName/files/xxx.apk
        apkFile = new File(getExternalFilesDir(null), "update.apk");
        //2.启动分线程，请求下载APK文件，下载过程中显示下载进度
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //得到连接对象
                    String path = "http://d2.eoemarket.com/app0/38/38199/apk/457255.apk";
                    URL url = new URL(path);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    //设置
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(10000);
                    connection.setReadTimeout(10000);
                    //连接
                    connection.connect();
                    //请求并得到响应码200
                    int responseCode = connection.getResponseCode();
                    if (responseCode == 200) {
                        //设置dialog的最大进度
                        dialog.setMax(connection.getContentLength());
                        //得到包含APK文件数据的InputStream
                        InputStream is = connection.getInputStream();
                        //创建指向ApkFile的FileOutputStream
                        FileOutputStream fos = new FileOutputStream(apkFile);
                        //边度边写
                        byte[] buffer = new byte[1024];
                        int len = -1;
                        while ((len = is.read(buffer)) != -1) {
                            fos.write(buffer, 0, len);
                            //显示下载进度
                            dialog.incrementProgressBy(len);
                        }
                        //下载完成，关闭流
                        is.close();
                        fos.close();
                    }
                    //关闭连接
                    connection.disconnect();
                    //3.主线程，移除diapog，启动安装
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dialog.dismiss();
                            installApk();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    dialog.dismiss();
                }
            }
        }).start();
    }

    /**
     * 启动安装apk
     */
    private void installApk() {
        Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
        intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        startActivity(intent);
    }

}
